package com.thirtydays.oral.common.listener;

import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlConnRunner;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.thirtydays.oral.common.service.DBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDateTime;

/**
 * TODO
 *
 * @author Dell
 * @version 1.0
 * @date 2021/5/17 17:58
 */
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "${mq.config.queue.sqlName}", autoDelete = "true"),
        exchange = @Exchange(value = "${mq.config.exchange}", type = ExchangeTypes.FANOUT)))
public class FanoutMsgConsumerListener {

    private static final Logger log = LoggerFactory.getLogger(FanoutMsgConsumerListener.class);
    @Autowired
    private Connection connection;

    @Autowired
    private DBService dbService;

    public FanoutMsgConsumerListener() {
    }

    @RabbitHandler
    public void process(String msg, Channel channel, Message message) throws IOException {
        try {
            log.info("收到消息：get fanout msg1 success msg = {}", msg);
            JSONObject parseObj = JSONUtil.parseObj(msg);
            String type = parseObj.getStr("type");
            if ("INSERT".equals(type)) {
                this.dbService.insert(this.connection, parseObj);
            }

            if ("UPDATE".equals(type)) {
                this.dbService.update(this.connection, parseObj);
            }

            if ("DELETE".equals(type)) {
                this.dbService.delete(this.connection, parseObj);
            }
        } catch (Exception var6) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            log.error("消息消费失败，get fanout msg1 failed msg = {}, {}", msg, var6);
        }

    }
}
